from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel
import httpx

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class CommandRequest(BaseModel):
    cmd: str

@app.post("/playground/api/command")
async def send_command(request: CommandRequest):
    """从服务器端发送命令到collector"""
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                "http://collector:5555/api/command",
                json={"cmd": request.cmd},
                headers={"Content-Type": "application/json"},
                timeout=10.0
            )
            
        if response.status_code == 200:
            return {"status": "success", "message": f"命令 {request.cmd} 发送成功"}
        else:
            raise HTTPException(
                status_code=response.status_code, 
                detail=f"collector响应错误: {response.text}"
            )
            
    except httpx.TimeoutException:
        raise HTTPException(status_code=504, detail="请求超时")
    except httpx.RequestError as e:
        raise HTTPException(status_code=503, detail=f"网络错误: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"内部错误: {str(e)}")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/playground")
async def read_index():
    return FileResponse('static/index.html')

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=80, log_config=None)
